import React, { Component, Fragment } from 'react';
import { message, Upload, Modal, Button, Icon, Spin } from 'antd';
import oss from '@/utils/oss';

const UE = window.UE;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

export default class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      UEditorId: '',
      iconVisible: false,
      musicVisible: false,
      videoVisible: false,

      iconSpinning: false,
      musicSpinning: false,
      videoSpinning: false,

      avatarList: [],
      audioList: [],
      videoList: [],

      previewImage: '', // 预览图片的url
      previewVisible: false, // 预览图片的弹窗状态
    };
    this.editor = null;
  }

  // componentWillReceiveProps(props) {
  //     if (!props.visible && this.editor) {
  //         this.editor.execCommand('cleardoc');
  //     }
  // }

  componentDidMount() {
    const time = new Date().getTime().toString();
    this.setState(
      {
        UEditorId: `UE-${time}`,
      },
      () => {
        this.registerUI();
      },
    );
  }

  // componentWillUnmount() {
  // this.editor.execCommand('cleardoc');
  // }

  registerUI = () => {
    const self = this;
    UE.registerUI('插入图片', (editor, uiName) => {
      //创建一个button
      let btnOne = new UE.ui.Button({
        //按钮的名字
        name: uiName,
        //提示
        title: uiName,
        //需要添加的额外样式，指定icon图标，这里默认使用一个重复的icon
        cssRules: 'background-position: -380px -0px;',
        //点击时执行的命令
        onclick: (s) => {
          //做自己的操作
          if (s === 'click') {
            self.setState({ iconVisible: true });
            return;
          } else {
            self.setState({ iconVisible: false });
          }
          editor.execCommand('inserthtml', s);
        },
      });

      //设置btn状态 进行 html 字符串传递
      self.setState({ btnOne });
      //当点到编辑内容上时，按钮要做的状态反射
      editor.addListener('selectionchange', () => {
        let state = editor.queryCommandState(uiName);
        if (state === -1) {
          btnOne.setDisabled(true);
          btnOne.setChecked(false);
        } else {
          btnOne.setDisabled(false);
          btnOne.setChecked(state);
        }
      });
      return btnOne;
    });
    // UE.registerUI('插入音频', (editor, uiName) => {
    //   //创建一个button
    //   let btnTwo = new UE.ui.Button({
    //     //按钮的名字
    //     name: uiName,
    //     //提示
    //     title: uiName,
    //     //需要添加的额外样式，指定icon图标，这里默认使用一个重复的icon
    //     cssRules: 'background-position: -18px -40px;',
    //     //点击时执行的命令
    //     onclick: s => {
    //       //做自己的操作
    //       if (s === 'click') {
    //         self.setState({ musicVisible: true });
    //         return;
    //       } else {
    //         self.setState({ musicVisible: false });
    //       }
    //       editor.execCommand('inserthtml', s);
    //     },
    //   });
    //   //设置btn状态 进行 html 字符串传递
    //   self.setState({ btnTwo });
    //   //当点到编辑内容上时，按钮要做的状态反射
    //   editor.addListener('selectionchange', () => {
    //     let state = editor.queryCommandState(uiName);
    //     if (state === -1) {
    //       btnTwo.setDisabled(true);
    //       btnTwo.setChecked(false);
    //     } else {
    //       btnTwo.setDisabled(false);
    //       btnTwo.setChecked(state);
    //     }
    //   });
    //   return btnTwo;
    // });
    // UE.registerUI('插入视频', (editor, uiName) => {
    //   //创建一个button
    //   let btnThree = new UE.ui.Button({
    //     //按钮的名字
    //     name: uiName,
    //     //提示
    //     title: uiName,
    //     //需要添加的额外样式，指定icon图标，这里默认使用一个重复的icon
    //     cssRules: 'background-position: -320px -20px;',
    //     //点击时执行的命令
    //     onclick: s => {
    //       console.log('点击时执行的命令 s is', s);
    //       //做自己的操作
    //       if (s === 'click') {
    //         self.setState({ videoVisible: true });
    //         return;
    //       } else {
    //         self.setState({ videoVisible: false });
    //       }
    //       editor.execCommand('inserthtml', s);
    //     },
    //   });
    //   //设置btn状态 进行 html 字符串传递
    //   self.setState({ btnThree });
    //   //当点到编辑内容上时，按钮要做的状态反射
    //   editor.addListener('selectionchange', () => {
    //     let state = editor.queryCommandState(uiName);
    //     if (state === -1) {
    //       btnThree.setDisabled(true);
    //       btnThree.setChecked(false);
    //     } else {
    //       btnThree.setDisabled(false);
    //       btnThree.setChecked(state);
    //     }
    //   });
    //   return btnThree;
    // });

    this.initEditor();
  };

  // 初始化编辑器

  initEditor = () => {
    const { SingleInfoData, mode, onChange } = this.props;
    const { UEditorId } = this.state;

    this.editor = UE.getEditor(UEditorId);
    this.editor.ready((ueditor) => {
      // if (!ueditor) {
      //     UE.delEditor(UEditorId);
      //     this.initEditor();
      // }
      // 当值改变时将值返回
      this.editor.addListener('contentChange', (e) => {
        onChange(this.editor.getContent());
      });
      // 初始化时设置默认值
      SingleInfoData && this.editor.setContent(SingleInfoData);
      mode === 3 ? this.editor.setDisabled() : this.editor.setEnabled();
    });
  };

  // 上传前的验证
  beforeUpload = (file, type) => {
    const mimeType = ['gif', 'png', 'jpeg', 'bmp', 'jpg'];
    const musicFormat = ['ogg', 'mp3'];
    const videoFormat = ['webm', 'mp4', 'ogg'];
    const fileFormat = [
      'txt',
      'ppt',
      'pptx',
      'pps',
      'ppsx',
      'doc',
      'docx',
      'xls',
      'xlsx',
      'pdf',
      'wps',
      'zip',
      'rar',
      '7z',
    ];

    const isJPG = mimeType.includes(file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase());
    const isMusic = musicFormat.includes(
      file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase(),
    );
    const isVideo = videoFormat.includes(
      file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase(),
    );
    const isFile = [...mimeType, ...musicFormat, ...videoFormat, ...fileFormat].includes(
      file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase(),
    );

    if (type === 'avatar') {
      if (!isJPG) {
        message.error('您只能上传图片类型为jpg、png、bmp、gif的图片');
      }
      let imageSize = '';
      imageSize = file.size / 1024 / 1024 < 2;
      if (!imageSize) {
        message.error('图片大小必须小于2M！');
      }

      return isJPG && imageSize;
    } else if (type === 'audio') {
      if (!isMusic) {
        message.error(`您只能上传音频类型为mp3、ogg的音频`);
      }
      const isLtSize = file.size / 1024 / 1024 < 4;
      if (!isLtSize) {
        message.error('上传音频文件最大不能超过4M！');
      }
      return isMusic && isLtSize;
    } else if (type === 'video') {
      if (!isVideo) {
        message.error(`您只能上传视频类型为mp4、webm、ogg的视频`);
      }
      const isLtSize = file.size / 1024 / 1024 < 10;
      if (!isLtSize) {
        message.error('上传视频文件最大不能超过10M！');
      }
      return isVideo && isLtSize;
    } else if (!isFile) {
      message.error(`不支持上传此格式的文件`);
    }
  };

  // 自定义封面上传
  handleCustomRequest = (options, type) => {
    const Name = options.file.name.slice(0, options.file.name.indexOf('.'));
    const ExtName = options.file.name.slice(options.file.name.lastIndexOf('.'));

    if (type === 'avatar') {
      this.setState({ iconSpinning: true });
      oss.ucuxin.uploader(
        {
          options,
          // attachmentStr: `{"Path": "wwnpc","AttachType": 1, "ExtName": ".${ExtName}","ResizeMode": 1,"SImgResizeMode": 2, "CreateThumb": true, "Width": 100, "Height": 100,"SHeight": 50,"SWidth": 50 }`,
          attachmentStr: `{"Path":"","AttachType":1,"Name":'${Name}',"ExtName":'${ExtName}',"ResizeMode":1,"SImgResizeMode":2,"CreateThumb":false}`,
          autoResizeLargeImage: true,
        },
        (res) => {
          if (res.Ret === 0) {
            message.success('上传成功！');
            this.setState({ iconSpinning: false });
            const { avatarList } = this.state;
            const obj = {
              uid: res.Data.Url,
              status: 'done',
              name: options.file.name,
              url: res.Data.Url,
              thumbUrl: res.Data.ThumbUrl,
            };
            avatarList.push(obj);
            this.setState({ avatarList });
          } else {
            message.error('上传失败！');
          }
        },
      );
    } else if (type === 'audio') {
      this.setState({ musicSpinning: true });
      oss.ucuxin.uploader(
        {
          options,
          attachmentStr: `{"Path": "wwnpc","AttachType": 2, "ExtName":  ".${ExtName}","ResizeMode": 1,"SImgResizeMode": 2 }`,
          cropRate: '',
        },
        (res) => {
          if (res.Ret === 0) {
            message.success('上传成功！');
            this.setState({ musicSpinning: false });
            const { audioList } = this.state;
            const obj = {
              uid: res.Data.Url,
              status: 'done',
              name: options.file.name,
              url: res.Data.Url,
              thumbUrl: res.Data.ThumbUrl,
            };
            audioList.push(obj);
            this.setState({ audioList });
          } else {
            message.error('上传失败！');
          }
        },
      );
    } else if (type === 'video') {
      this.setState({ videoSpinning: true });
      oss.ucuxin.uploader(
        {
          options,
          attachmentStr: `{"Path": "wwnpc","AttachType": 4, "ExtName":  ".${ExtName}","ResizeMode": 1,"SImgResizeMode": 2 }`,
          cropRate: '',
        },
        (res) => {
          if (res.Ret === 0) {
            message.success('上传成功！');
            this.setState({ videoSpinning: false });
            const { videoList } = this.state;
            const obj = {
              uid: res.Data.Url,
              status: 'done',
              name: options.file.name,
              url: res.Data.Url,
              thumbUrl: res.Data.ThumbUrl,
            };
            videoList.push(obj);
            this.setState({ videoList });
          } else {
            message.error('上传失败！');
          }
        },
      );
    } else if (type === 'file') {
      this.setState({ fileSpinning: true });
      oss.ucuxin.uploader(
        {
          options,
          attachmentStr: `{"Path": "wwnpc","AttachType": 9, "ExtName": ".${ExtName}","ResizeMode": 1,"SImgResizeMode": 2  }`,
          cropRate: '',
        },
        (res) => {
          if (res.Ret === 0) {
            this.setState({ fileSpinning: false });
            const { fileList } = this.state;
            const obj = {
              uid: res.Data.Url,
              status: 'done',
              name: options.file.name,
              url: res.Data.Url,
              thumbUrl: res.Data.ThumbUrl,
            };
            fileList.push(obj);
            this.props.changeFileList(fileList);
          } else {
          }
        },
      );
    }
  };

  // 删除文件列表
  removeFile = (file, type) => {
    const { avatarList, audioList, videoList } = this.state;
    const { mode } = this.props;
    if (type === 'avatar') {
      const avatarListListData = avatarList.filter((item) =>
        mode === 2 ? file.Url !== item.Url : file.url !== item.url,
      );
      this.setState({
        avatarList: avatarListListData,
      });
    } else if (type === 'audio') {
      const audioListData = audioList.filter((item) =>
        mode === 2 ? file.Url !== item.Url : file.url !== item.url,
      );
      this.setState({
        audioList: audioListData,
      });
    } else if (type === 'video') {
      const videoListData = videoList.filter((item) =>
        mode === 2 ? file.Url !== item.Url : file.url !== item.url,
      );
      this.setState({
        videoList: videoListData,
      });
    }
  };

  // 点击预览图片
  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  // 转换图片格式
  getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };

  //点击弹窗的确定按钮
  clickSure = (type) => {
    if (type === 'avatar') {
      let imgstr = '';
      if (this.state.avatarList && this.state.avatarList.length !== 0) {
        for (let i = 0; i < this.state.avatarList.length; i += 1) {
          imgstr += `<div><img src=${this.state.avatarList[i].url} /></div>`;
        }
        this.state.btnOne.onclick(
          // 点击创建的自定义按钮，传入dom模板
          `${imgstr}`,
        );
      } else {
        message.info('请选择要插入的图片');
      }
    } else if (type === 'audio') {
      let audioStr = '';

      if (this.state.audioList && this.state.audioList.length !== 0) {
        for (let i = 0; i < this.state.audioList.length; i += 1) {
          audioStr += `<p><audio controls="controls"  src='${this.state.audioList[i].url}'>&nbsp</audio></p>`;
        }
        this.state.btnTwo.onclick(`${audioStr}`);
      } else {
        message.info('请选择要插入的音频');
      }
    } else if (type === 'video') {
      let videoStr = '';

      if (this.state.videoList && this.state.videoList.length !== 0) {
        for (let i = 0; i < this.state.videoList.length; i += 1) {
          videoStr += `<div style="width:100%;display:flex;position:relative">
                            <video controls="false" width="100%" height="240" src='${this.state.videoList[i].url}' 
                        webkit-playsinline="true" playsinline="true">&nbsp</video></div>`;
        }
        this.state.btnThree.onclick(`${videoStr}`);
      } else {
        message.info('请选择要插入的视频');
      }
    }

    this.setState({
      avatarList: [],
      audioList: [],
      videoList: [],
    });
  };

  // 点击弹窗的取消按钮
  clickCancel = (type) => {
    if (type === 'video') {
      this.setState({ videoVisible: false, videoList: [] });
    } else if (type === 'avatar') {
      this.setState({ iconVisible: false, avatarList: [] });
    } else if (type === 'audio') {
      this.setState({ musicVisible: false, audioList: [] });
    }
  };

  render() {
    return (
      <div>
        <script
          id={this.state.UEditorId}
          name="content"
          type="text/plain"
          style={{ lineHeight: '20px', width: '600px', height: '300px' }}
        />
        {/*插入视频*/}
        <Modal
          visible={this.state.videoVisible}
          wrapClassName="vertical-center-modal"
          title="请插入视频"
          onCancel={() => this.clickCancel('video')}
          onOk={() => this.clickSure('video')}
          maskClosable={false}
          // bodyStyle={{textAlign:'center'}}
        >
          <Upload
            name="video"
            fileList={this.state.videoList}
            beforeUpload={(file) => this.beforeUpload(file, 'video')}
            customRequest={(options) => this.handleCustomRequest(options, 'video')}
            onRemove={(options) => this.removeFile(options, 'video')}
            accept="video/webm,video/mp4,video/ogg"
          >
            <Button>
              <Icon type="upload" /> 上传视频
            </Button>
          </Upload>
          <Spin
            style={{ marginTop: 10 }}
            indicator={antIcon}
            spinning={this.state.videoSpinning}
          ></Spin>
        </Modal>
        {/*插入图片*/}
        <Modal
          visible={this.state.iconVisible}
          wrapClassName="vertical-center-modal"
          title="请插入图片"
          onCancel={() => this.clickCancel('avatar')}
          onOk={() => this.clickSure('avatar')}
          bodyStyle={{ minHeight: 136 }}
          maskClosable={false}
        >
          <Upload
            className="avatar-uploader"
            fileList={this.state.avatarList}
            name="avatar"
            listType="picture-card"
            beforeUpload={(file) => this.beforeUpload(file, 'avatar')}
            customRequest={(options) => this.handleCustomRequest(options, 'avatar')}
            onRemove={(options) => this.removeFile(options, 'avatar')}
            onPreview={this.handlePreview}
            accept="image/gif,image/png,image/jpeg,image/bmp"
          >
            {this.state.avatarList && this.state.avatarList.length >= 3 ? null : (
              <Spin
                style={{ marginTop: 10 }}
                indicator={antIcon}
                spinning={this.state.iconSpinning}
              >
                <div>
                  <Icon type="plus" />
                  <div className="ant-upload-text">上传图片</div>
                </div>
              </Spin>
            )}
          </Upload>
          <Modal
            visible={this.state.previewVisible}
            footer={null}
            maskClosable={false}
            onCancel={() => this.setState({ previewVisible: false })}
          >
            <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
          </Modal>
        </Modal>
        {/*插入音频*/}
        <Modal
          visible={this.state.musicVisible}
          wrapClassName="vertical-center-modal"
          title="请插入音频"
          maskClosable={false}
          onCancel={() => this.clickCancel('audio')}
          onOk={() => this.clickSure('audio')}
          // bodyStyle={{textAlign:'center'}}
        >
          <Upload
            name="audio"
            fileList={this.state.audioList}
            beforeUpload={(file) => this.beforeUpload(file, 'audio')}
            customRequest={(options) => this.handleCustomRequest(options, 'audio')}
            onRemove={(options) => this.removeFile(options, 'audio')}
            accept="audio/ogg,audio/mp3"
          >
            <Button>
              <Icon type="upload" /> 上传音频
            </Button>
          </Upload>
          <Spin style={{ marginTop: 10 }} indicator={antIcon} spinning={this.state.musicSpinning} />
        </Modal>
      </div>
    );
  }
}
